from flask import Blueprint, jsonify, request
import os
from utils.data import get_data
from db import db1
from utils.myfiles import myf

bp_work = Blueprint("work", __name__)


# 照片上传
# @bp_work.route('/jpgupload', methods=['POST'])
# def jpgupload():
#     file = request.files['file']
#     file.save(os.path.join('./static/upload/', file.filename))
#     return jsonify({'code': 200, 'pic': file.filename})
#
#
# # 视频上传
# @bp_work.route('/vedioupload', methods=['POST'])
# def vedioupload():
#     file = request.files['file']
#     id = request.form['id']
#     path = './static/upload/' + str(id)
#     if not os.path.exists(path):
#         os.mkdir(path)
#     file.save(os.path.join(path, file.filename))
#     # 返回结果
#     return jsonify({"code": 200, 'url': '/static/upload' + '/' + str(id) + '/' + file.filename})


# 文件上传
@bp_work.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    cityid = request.form['cityid']
    # 创建文件夹
    myf.file_mkdir(cityid)
    # 图片上传
    file.save(os.path.join('./static/upload/' + str(cityid), file.filename))
    return jsonify({"code": 200, 'url': '/static/upload/' + str(cityid) + '/' + file.filename})


# 城市接口
@bp_work.route('/cityM', methods=['GET'])
def cityM():
    sql = "select * from city"
    res = db1.findall(sql)
    return jsonify({"code": 200, "list": res})


# product添加接口
@bp_work.route('/proM', methods=['POST', "GET"])
def proM():
    if request.method == "POST":
        data = get_data()
        sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')" % (
            data['title'], float(data['price']), int(data['city_id']), data['pic'])
        db1.insert(sql)
        return jsonify({"code": 200})
    else:
        # 获取当前页
        page = request.args.get('page')
        # 每页面显示多少条
        page_size = 2
        # 计算开始下标
        start = (int(page) - 1) * page_size

        # 根据分类id查询分类下商品
        cityid = request.args.get('cityid')
        # 排序
        sort = request.args.get('sort')
        if cityid == '0':
            sql = "select * from product order by id %s limit %d,%d" % (sort, start, page_size)
            # 查询总条数
            sql1 = "select count(id) from product"
            res = db1.find(sql1)
            total = res['count(id)']
        else:
            sql = "select * from product where city_id=%d order by id %s limit %d,%d" % (
                int(cityid), sort, start, page_size)
            # 查询总条数
            sql1 = "select count(id) from product where city_id=%d" % (int(cityid))
            res = db1.find(sql1)
            total = res['count(id)']

        res = db1.findall(sql)
        return jsonify({"code": 200, 'list': res, 'total': total})
